const Router = require('koa-router')()
const http = require("http");
const path = require("path");
const fse = require("fs-extra");

const UPLOAD_DIR = path.resolve(__dirname, "..", "target");

Router.post('/upload', async (ctx) => {
  let chunk = ctx.request.files.chunk;
  let {
    hash,
    filename
  } = ctx.request.body

  const chunkDir = path.resolve(UPLOAD_DIR, filename);

  // 切片目录不存在，创建切片目录
  if (!fse.existsSync(chunkDir)) {
    await fse.mkdirs(chunkDir);
  }

  await fse.move(chunk.path, `${chunkDir}/${hash}`);
  ctx.body = 'upload success'
})

Router.post('/merge', async (ctx) => {
  console.log('----------------');

  const data = await resolvePost(ctx.req);
  console.log('data:', data);

  // const {
  //   filename,
  //   size
  // } = data;
  // console.log(filename, size);

  // const filePath = path.resolve(UPLOAD_DIR, `${filename}`);
  // await mergeFileChunk(filePath, filename);
  // ctx.body = JSON.stringify({
  //   code: 0,
  //   message: "file merged success"
  // })
})

const resolvePost = req =>
  new Promise(resolve => {
    let chunk = "";
    
    req.on("data", data => {
      console.log(data);

      chunk += data;
    });
    req.on("end", () => {
      resolve(JSON.parse(chunk));
    });
  });

const pipeStream = (path, writeStream) =>
  new Promise(resolve => {
    const readStream = fse.createReadStream(path);
    readStream.on("end", () => {
      fse.unlinkSync(path);
      resolve();
    });
    readStream.pipe(writeStream);
  });

// 合并切片
const mergeFileChunk = async (filePath, filename, size) => {
  const chunkDir = path.resolve(UPLOAD_DIR, filename);
  const chunkPaths = await fse.readdir(chunkDir);
  // 根据切片下标进行排序
  // 否则直接读取目录的获得的顺序可能会错乱
  chunkPaths.sort((a, b) => a.split("-")[1] - b.split("-")[1]);
  await Promise.all(
    chunkPaths.map((chunkPath, index) =>
      pipeStream(
        path.resolve(chunkDir, chunkPath),
        // 指定位置创建可写流
        fse.createWriteStream(filePath, {
          start: index * size,
          end: (index + 1) * size
        })
      )
    )
  );
  fse.rmdirSync(chunkDir); // 合并后删除保存切片的目录
};


Router.use('/', Router.routes(), Router.allowedMethods())

module.exports = Router